package cn.sciento.boot.tenant.hiam.app.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import cn.sciento.boot.platform.lov.handler.LovValueHandle;
import cn.sciento.boot.tenant.constant.TenantInitType;
import cn.sciento.boot.tenant.hiam.app.service.TenantInitConfigService;
import cn.sciento.boot.tenant.hiam.domain.entity.TenantInitConfig;
import cn.sciento.boot.tenant.hiam.infra.mapper.TenantInitConfigMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TenantInitConfigServiceImpl implements TenantInitConfigService {
  @Autowired
  private TenantInitConfigMapper tenantInitConfigMapper;
  
  @Autowired
  private LovValueHandle lovValueHandle;
  
  public List<TenantInitConfig> selectTenantInitConfigList(TenantInitConfig tenantInitConfig) {
    return this.tenantInitConfigMapper.selectTenantInitConfig(tenantInitConfig);
  }
  
  public Map<String, Map<String, List<TenantInitConfig>>> selectTenantInitConfigMap() {
    Map<String, Map<String, List<TenantInitConfig>>> resultMap = new HashMap<>();
    List<TenantInitConfig> tenantInitConfigs = this.tenantInitConfigMapper.selectTenantInitConfig(new TenantInitConfig());
    if (CollectionUtils.isEmpty(tenantInitConfigs))
      return resultMap; 
    tenantInitConfigs = (List<TenantInitConfig>)this.lovValueHandle.process(null, tenantInitConfigs);
    Map<String, List<TenantInitConfig>> initTypeMap = (Map<String, List<TenantInitConfig>>)tenantInitConfigs.stream().collect(Collectors.groupingBy(item -> item.getInitType()));
    List<TenantInitConfig> createList = initTypeMap.get(TenantInitType.CREATE.name());
    List<TenantInitConfig> updateList = initTypeMap.get(TenantInitType.UPDATE.name());
    if (CollectionUtils.isNotEmpty(createList)) {
      Map<String, List<TenantInitConfig>> processorTypeMap = (Map<String, List<TenantInitConfig>>)createList.stream().collect(Collectors.groupingBy(item -> item.getProcessorType()));
      resultMap.put(TenantInitType.CREATE.name(), processorTypeMap);
    } 
    if (CollectionUtils.isNotEmpty(updateList)) {
      Map<String, List<TenantInitConfig>> processorTypeMap = (Map<String, List<TenantInitConfig>>)createList.stream().collect(Collectors.groupingBy(item -> item.getProcessorType()));
      resultMap.put(TenantInitType.UPDATE.name(), processorTypeMap);
    } 
    return resultMap;
  }
}
